import {exec, OutputMode} from './exec.ts'

export interface makeParams {
  withAnswer: boolean, 
  take: number, 
  seed: number
}

export interface arithmeticItem {
  leftOperand: number,
  operator: "+" | "-",
  rightOperand: number
  answer? : number | ""
}

const arithmeticMaker = `${Deno.cwd()}/bin/children-arithmetic`

export const makeArithmeticItems  = async (p: makeParams) : Promise<arithmeticItem[]> => {
  const {withAnswer, take, seed} = p
  const withAnswerBoolValue = withAnswer ? "True" : "False"
  if (take < 0 || isNaN(take)) {
    throw Error(`0<take`)
  }
  if (seed <0 || seed > 100 || isNaN(seed)) {
    throw Error(`0<seed<100`)
  }
  const command = `${arithmeticMaker} -a ${withAnswerBoolValue} -n ${take} ${seed}`
  console.log(`make command=>${command}`)
  const outputResult = await exec(command, {output: OutputMode.Capture});
  if (!outputResult.status.success) {
    throw Error(`生成失败`)
  }
  const arithmeticItems: arithmeticItem[] = JSON.parse(outputResult.output).map((item: string) => {
    const [problem, answer] = item.split("=")
    let operator : "+" | "-"
    if (problem.includes("+")) {
      operator = "+"
    } else {
      operator = "-"
    }
    const [leftOperand, rightOperand] = problem.split(operator)
    let row = {
      leftOperand: parseInt(leftOperand),
      operator,
      rightOperand: parseInt(rightOperand),
      answer: answer && parseInt(answer)
    }
    return row
  })
  return arithmeticItems
}